package com.degon.hsyl.musicplayview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MusicPlayView extends View {

    //坐标原点x
    private float mBasePointX;

    //坐标原点y
    private float mBasePointY;

    //指针的数量，默认10
    private int mPointNum;

    //指针的间隙，默认5dp
    private float mPointSpace;

    //每个指针的宽度，默认5dp
    private float mPointWidth;

    //指针的颜色
    private int mPointColor = Color.RED;

    //指针的集合
    private List<Pointer> mPoints;

    //指针开始/停止控制
    private boolean mIsPlaying = false;

    //播放线程
    private Thread mPlayThread;

    //指针波动速度
    private int mPointSpeed;

    //画笔
    private Paint mPaint;

    public MusicPlayView(Context context) {
        super(context);
        initPaint();
    }

    public MusicPlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //取出自定义属性
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.musicPlayViewAttr);
        mPointNum = ta.getInt(R.styleable.musicPlayViewAttr_point_num, 10);
        mPointWidth = dp2px(getContext(), ta.getFloat(R.styleable.musicPlayViewAttr_point_width, 5f));
        mPointColor = ta.getColor(R.styleable.musicPlayViewAttr_point_color, Color.RED);
        mPointSpeed = ta.getInt(R.styleable.musicPlayViewAttr_point_speed, 40);
        initPaint();
    }

    public MusicPlayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.musicPlayViewAttr);
        mPointNum = ta.getInt(R.styleable.musicPlayViewAttr_point_num, 10);
        mPointWidth = dp2px(getContext(), ta.getFloat(R.styleable.musicPlayViewAttr_point_width, 5f));
        mPointColor = ta.getColor(R.styleable.musicPlayViewAttr_point_color, Color.RED);
        mPointSpeed = ta.getInt(R.styleable.musicPlayViewAttr_point_speed, 40);
        initPaint();
    }

    /**
     * 初始化画笔
     */
    private void initPaint() {
        mPoints = new ArrayList<>();
        //绘制虚线
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(mPointColor);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(mPointWidth);
        mPaint.setPathEffect(new DashPathEffect(new float[]{25, 15}, 0));//虚线间隔
        setLayerType(LAYER_TYPE_SOFTWARE, null);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        //获取逻辑原点的y
        mBasePointY = getHeight() - getPaddingBottom();
        Random random = new Random();
        if (mPoints != null) {
            mPoints.clear();
        }
        for (int i = 0; i < mPointNum; i++) {
            //随机高度
            mPoints.add(new Pointer((float) (0.1 * (random.nextInt(10) + 1) * (getHeight() - getPaddingBottom() - getPaddingTop()))));
        }
        //计算每个指针之间的间隔 view宽度 - 左右的padding - 所有指针总共的宽度 再除以多少个间隔
        mPointSpace = (getWidth() - getPaddingLeft() - getPaddingRight() - mPointWidth * mPointNum) / (mPointNum - 1);
    }

    //绘制
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //指针x位置
        mBasePointX = 0f + getPaddingLeft() + mPointWidth / 2;
        //绘制每一个指针
        for (int i = 0; i < mPoints.size(); i++) {
            //绘制虚线
            float[] pts = {mBasePointX, getHeight(), mBasePointX, (mBasePointY - mPoints.get(i).getHeight())};//从下往上动画
            canvas.drawLines(pts, mPaint);
            //更新指针位置
            mBasePointX += (mPointSpace + mPointWidth);
        }
    }

    /**
     * 开始播放
     */
    public void start() {
        setVisibility(VISIBLE);
        if (!mIsPlaying) {
            if (mPlayThread == null) {
                mPlayThread = new Thread(new PlayRunnable());
                mPlayThread.start();
            }
            mIsPlaying = true;//控制子线程中的循环
        }
    }

    public void stop() {
        setVisibility(INVISIBLE);
        mIsPlaying = false;
        invalidate();
    }

    /**
     * 子线程，循环改变每个指针的高度
     */
    public class PlayRunnable implements Runnable {
        @Override
        public void run() {
            for (float i = 0; i < Integer.MAX_VALUE; ) {
                try {
                    for (int j = 0; j < mPoints.size(); j++) {
                        float rate = (float) Math.abs(Math.sin(i + j));//随机数
                        mPoints.get(j).setHeight((mBasePointY - getPaddingTop()) * rate);//每个指针的高度
                    }
                    Thread.sleep(mPointSpeed);
                    //开始/暂停
                    if (mIsPlaying) {
                        myHandler.sendEmptyMessage(0);
                        i += 0.1;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 更新UI
     */
    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            invalidate();
        }
    };

    /**
     * dp转px
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dp2px(Context context, float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());
    }
}
